import * as user from '@/api/user'
import * as types from '../action_type';
import router from '@/router'

import { getLocal, setLocal } from '@/utils/local.js';
import per from '@/router/per'

const filterRouter = (authList) => {
  let auths = authList.map(auth => auth.auth);
  // debugger
  function filter(routes) {
    return routes.filter(route => {
      if(auths.includes(route.meta.auth)) {
        if(route.children) {
          route.children = filter(route.children);
        }
        return route
      }
    })
  }
  return filter(per)
}

export default {
  state: {
    userInfo: {},
    hasPermission: false,
    menuPermission:false,//代表着菜单权限
  },
  mutations: {
    [types.SET_USER](state, info) {
      state.userInfo = info;
      if(info && info.token) {
        setLocal('token', info.token);
      }else{
        localStorage.clear('token');
      }
    },
    [types.SET_PERMISSION](state, has) {
      state.hasPermission = has;
    },
    [types.SET_MENU_PERMISSION](state, has) {
      state.menuPermission = has;
    }
  },
  actions: {
    [types.SET_USER]({commit}, {payload, hasPermission}) {
      commit(types.SET_USER, payload);
      commit(types.SET_PERMISSION, hasPermission);
    },
    async [types.USER_LOGIN]({ commit, dispatch }, payload) {
      try {
        let res = await user.login(payload);console.log('res', res)
        dispatch(types.SET_USER, {payload:res.data, hasPermission: true})
        if(res.err === 0){
          router.push('/');
        }
      } catch (error) {
        return Promise.reject(error);
      }
    },
    async [types.USER_VALIDATE]({dispatch}) {
      if(!getLocal('token')) return false;
      try {
        let res = await user.validate();
        dispatch(types.SET_USER, {payload: res.data, hasPermission: true});
        return true;
      } catch (error) {
        dispatch(types.SET_USER,{payload:{}, hasPermission:false});
        return false;
      }
    },
    async [types.USER_LOGOUT]({dispatch}) {
      dispatch(types.SET_USER,{payload:{}, hasPermission:false});
    },
    async [types.ADD_ROUTE]({commit, state}) {
      let authList = state.userInfo.authList;
      console.log('authList', authList);
      if(authList) {
        debugger
        let routes = filterRouter(authList);console.log(routes, 'routes')
        let route = router.options.routes.find(item=>item.path === '/manager');
        route.children = routes;
        router.addRoutes([route]);
        commit(types.SET_MENU_PERMISSION, true)
      }else{
        commit(types.SET_MENU_PERMISSION, true)
      }
    }
  }
}